package net.zjitc.controller;

import net.zjitc.domain.MessageConstant;
import net.zjitc.domain.Result;
import net.zjitc.domain.ResultPage;
import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody User user) {
        try {
            userService.add(user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ADD_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS, null);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {


        try {
            userService.deleteById(id);
        } catch (Exception e) {
            return new Result(false, MessageConstant.DELETE_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS, null);

    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {

        User page = null;
        try {
            page = userService.findById(id);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, page);
    }


    @PutMapping
    public Result update(@RequestBody User user) {
        try {
            userService.updateUser(user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.EDIT_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.EDIT_USER_SUCCESS, null);
    }

    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage,
                          @PathVariable("pageSize") int pageSize,
                          @RequestBody User user) {
        ResultPage<User> page = null;
        try {
            page = userService.findPage(currentPage, pageSize, user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, page);
    }
}
